const {
  BrowserWindow,
  ipcMain,
  globalShortcut,
  screen,
  app,
} = require("electron");
const path = require("path");
const {
  getSelectedText,
  activeWindowName,
  isDev,
  keycode,
} = require("./utils.cjs");
const logger = require("./log.cjs");
const windowManager = require("./windowMamager.cjs");
const iohook = require("./win32/iohook/index.cjs");
let stopTimer = null;
let offset = 4;
let isUseUnderLineWord = true;
let scaleFactor = 1;
let selectText = "";
let isSetPropmpt = false;
let keyCodeStack = new Set();
let mouseInitPos = {
  x: 0,
  y: 0,
};
let mouseUpPos = {
  x: 0,
  y: 0,
};
let iconWin;
let curWinName = "";
let iconPopUpType = "mouseUp";
let isClickIcon = false;
let defauleDelay = 80;
const expandDelay = 250;

function IconWindowInit() {
  try {
    iohook.start(false);
    // 监听全局鼠标事件
    iohook.on("mousedown", mouseDown);
    iohook.on("mouseup", mouseUp);
    iohook.on("mouseclick", mouseClick);
    iohook.on("keydown", keydown);
    iohook.on("keyup", keyup);
    windowManager.add("iconWin", iconWin);
    // 创建一个托盘实例，并指定图标的路径
    iconWin = createWindow();
    iconWin.loadURL(
      isDev()
        ? "http://localhost:5173/#/icon-tool"
        : `file://${path.join(__dirname, "../dist/index.html")}#/icon-tool`
    );
    globalShortcut.register("Control+Alt+Space", async () => {
      toggleShowKey()
    });
  } catch (error) {
    logger.error(error);
  }
}

const createWindow = () => {
  win = new BrowserWindow({
    width: 30 * 9,
    height: 100,
    // width: 625,
    // height: 225,
    center: true,
    skipTaskbar: false,
    resizable: false,
    transparent: true,
    frame: false,
    show: true,
    opacity: 0,
    autoHideMenuBar: true,
    alwaysOnTop: true,
    focusable: true,
    webPreferences: {
      contextIsolation: false,
      webSecurity: false,
      //  渲染进程 开启node模块，使得JS中可以使用node的model
      nodeIntegration: true,
      // 开启 remote 模块
      enableBlinkFeatures: true,
      enableRemoteModule: true
      // 控制上下文隔离
      // contextIsolation:false,
    },
  });
  handleIPC();
  win.setSkipTaskbar(true);
  const primaryDisplay = screen.getPrimaryDisplay();
  scaleFactor = primaryDisplay.scaleFactor;
  // win.webContents.openDevTools();
  return win;
};
async function mouseClick(event) {
  if (windowManager.get("searchWin").isAlwaysOnTop()) {
    windowManager.get("searchWin").setAlwaysOnTop(false);
  }
}
async function getUnderSelect() {
  if (!isUseUnderLineWord) {
    return await getSelectedText(
      isDelay(curWinName) ? expandDelay : defauleDelay
    );
  }
}
async function keydown(event) {
  switch (event.keycode) {
    case keycode.c:
      keyCodeStack.add(keycode.c);
      break;
    case keycode.ctrl:
      keyCodeStack.add(keycode.ctrl);
      break;
    case keycode.v:
      keyCodeStack.add(keycode.v);
      break;
  }
}
async function keyup(event) {
  switch (event.keycode) {
    case keycode.c:
      keyCodeStack.delete(keycode.c);
      break;
    case keycode.ctrl:
      keyCodeStack.delete(keycode.ctrl);
      break;
    case keycode.v:
      keyCodeStack.delete(keycode.v);
      break;
  }
}

function toggleShowKey() {
  isUseUnderLineWord=!isUseUnderLineWord;
  if (isUseUnderLineWord) {
    iconWin && iconWin.setOpacity(1);
    iconWin.setFocusable(false);
    showIcon(mouseUpPos.x, mouseUpPos.y, "hotKey");
  }else {
    iconWin && iconWin.setOpacity(0);
  }
  let setWin = windowManager.get("settingWin");
  setWin.webContents.send("changeIconToggle", {
    value: isUseUnderLineWord
  });
}
function handleIPC() {
  ipcMain.handle("msg", async function (e, ...args) {
    if (iconPopUpType === "hotKey") {
      selectText = await getUnderSelect();
    }
    isClickIcon = true;
    setTimeout(() => {
      const searchWin = windowManager.get("searchWin");
      searchWin.setOpacity(1);
      searchWin.show();
      searchWin.setAlwaysOnTop(true);
      logger.info(selectText);
      searchWin.webContents.send("preSend", {
        selectedText: selectText,
      });
      windowManager.get("settingWin").hide();
    }, 100);
  });
  ipcMain.handle("setHotKey", function (e, ...args) {
    if(args[0].oldKey) globalShortcut.unregister(args[0].oldKey)
    globalShortcut.register(args[0].newKey, async () => {
      toggleShowKey()
    });
  });
  ipcMain.handle("preSetPropmpt", function (e, ...args) {
    isSetPropmpt = true;
    const bounds = iconWin.getBounds();
    if (bounds.width < 400) {
      iconWin.setBounds({ ...args[0] });
    } else {
      iconWin.setBounds({ height: args[0].height });
    }
  });
  ipcMain.handle("setPropmpt", function (e, ...args) {
    isSetPropmpt = false;
    iconWin.setBounds({ ...args[0] });
    iconWin.webContents.send("changeIconNum", {
      name: curWinName,
      value: { ...args[0] }.value
    });
  });
  ipcMain.handle("stopIcon", function (e, ...args) {
    // clearTimeout(stopTimer);
    isUseUnderLineWord = args[0];
    // stopTimer = setTimeout(() => {
    //   isUseUnderLineWord = true;
    // }, args[0]);
  });
}

// 显示图标
function showIcon(x, y, type) {
  iconPopUpType = type;
  console.log(selectText.trim().length);
  if (type === "mouseUp") {
    if (selectText.trim().length === 0) {
      return;
    }
  }
  if (iconWin) {
    iconWin.setPosition(
      parseInt((x + 14) / scaleFactor),
      parseInt((y + 14) / scaleFactor)
    );
    iconWin.setAlwaysOnTop(true);
    iconWin.setOpacity(1);
  }
}

async function mouseDown(event) {
  curWinName = await activeWindowName();// 获取当前划词的应用
  iconWin.webContents.send("changeIcon", {
    name: curWinName,
  });
  mouseInitPos = event;
}
function isDelay(name) {
  const delayProgram = [
    "WPS Office",
    "word",
    "excel",
    "ppt",
    "HardwareMonitorWindow",
  ];

  for (let index = 0; index < delayProgram.length; index++) {
    const program = delayProgram[index];
    if (name.includes(program) || program.includes(name)) {
      return true;
    }
  }
  return false;
}

async function mouseUp(event) {
  mouseUpPos.x = event.x;
  mouseUpPos.y = event.y;
  if (
    Math.abs(event.x - mouseInitPos.x) > offset ||
    Math.abs(event.y - mouseInitPos.y) > offset
  ) {
    if (isUseUnderLineWord && !isSetPropmpt) {
      selectText = await getSelectedText(
        isDelay(curWinName) ? expandDelay : defauleDelay,
        keyCodeStack
      );
      showIcon(event.x, event.y, "mouseUp");
    }
    return;
  }

  if (iconWin.isFocused()) {
    return;
  }
  isClickIcon = false;
  if (!isClickIcon && !isSetPropmpt) {
    iconWin && iconWin.setOpacity(0);
  }
  iconWin.webContents.send("systemMouseUp");
}


module.exports = {
  IconWindowInit,
};
